package com.zazu.mycl.application.terminal;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.logging.Level;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

import com.zazu.mycl.application.ApplicationController;

public class MyClInputVetoListener implements VetoableChangeListener {

	public void vetoableChange(PropertyChangeEvent pce)
			throws PropertyVetoException {
	
		JTextArea ta = (JTextArea) pce.getSource();
		
		int caretPosition = ta.getCaretPosition();
		
		int lastline = ta.getLineCount()-1;
		
		//If the caret is in the last line, allow edits
		try {
			if(caretPosition >= ta.getLineStartOffset(lastline) && caretPosition <= ta.getLineEndOffset(lastline))
			{
				return;
			}
			else
			{
				ApplicationController.logger.log(Level.INFO, "Change Vetoed.");
				
				//Put the caret to the last line
				ta.setCaretPosition(ta.getText().length()-1);
				
				//Throw exception
				throw new PropertyVetoException("No change allowed.",pce);
			}
		} catch (BadLocationException e) {
			//Throw exception
			ApplicationController.logger.log(Level.INFO, "Change Vetoed.");
			throw new PropertyVetoException("No change allowed.",pce);
		}

	}

}
